package com.xnew.user.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.constant.Constant;
import com.xnew.encrypt.Sm3Encrypt;
import com.xnew.exception.CustomException;
import com.xnew.resource.bean.AuResource;
import com.xnew.resource.mapper.AuResourceMapper;
import com.xnew.bean.common.AuUserRole;
import com.xnew.role.mapper.AuRoleMapper;
import com.xnew.role.mapper.AuRoleResourceMapper;
import com.xnew.role.mapper.AuUserRoleMapper;
import com.xnew.user.mapper.AuUserMapper;
import com.xnew.utils.DateUtils;
import com.xnew.utils.IdUtils;
import com.xnew.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by lenovo on  三月
 */

@Service
@CacheConfig
@Transactional(rollbackFor = Exception.class)
public class AuUserService {

	@Autowired
	private AuUserMapper auUserMapper;
	@Autowired
	private AuUserRoleMapper auUserRoleMapper;
	@Autowired
	private AuRoleResourceMapper auRoleResourceMapper;
	@Autowired
	private AuRoleMapper auRoleMapper;
	@Autowired
	private AuResourceMapper auResourceMapper;

	private static final Logger logger = LoggerFactory.getLogger(AuUserService.class);

    public SysUserInfo findUserByName(String name) {
        return auUserMapper.findUserByUserName(name);
    }

    public List<AuUserRole> findRoleIdByUid(String uid) {
        return auUserRoleMapper.findRoleIdByUid(uid);
    }

    public List<String> findPermissionIdByRoleId(String roleId) {
        return auRoleResourceMapper.findPermissionIdByRoleId(roleId);
    }

    public String findRoleByRoleId(String roleId) {
        return auRoleMapper.findRoleByRoleId(roleId);
    }

    public AuResource findPermissionById(String id) {
        return auResourceMapper.findPermissionById(id);
    }
    
    /**
	 * 根据用户编号注销用户
	 * 
	 * @param user
	 * @param request
	 * @throws Exception
	 */
	public void cancelAuUserId(SysUserInfo user, HttpServletRequest request) throws Exception {
		if (!StringUtils.isBlank(user.getUserInfoNo())) {
			auUserMapper.updateStatusByAuId(Constant.AU_STATUE_NO, user.getUserInfoNo());
		}
	}

	public PageInfo<SysUserInfo> selectUserAll(Map<String, Object> map, HttpServletRequest request)
			throws Exception {

		String userName = map.get("AU_NAME") == null ? "" : map.get("AU_NAME").toString();
		map.put("userName", userName);
		PageHelper.startPage(Integer.parseInt(map.get("currentPage").toString()),
				Integer.parseInt(map.get("pageSize").toString()), true);
		List<SysUserInfo> userAll = auUserMapper.selectAll(map);
		final PageInfo<SysUserInfo> pageInfo = new PageInfo<SysUserInfo>(userAll);
		return pageInfo;
	}
	
	public List<Map<String, Object>> getRoleByUserId(String auId) {
		return auUserMapper.getRoleByUserId(auId);
	}

	public List<Map<String, Object>> getResourceByUserId(String auId) {
		return auUserMapper.getResourceByUserId(auId);
	}
	
	public void addUser(Map<String, Object> userParams, HttpServletRequest request) throws ParseException {
		String userId = IdUtils.getRandomIdByUUID();
		SysUserInfo user = new SysUserInfo();
		user.setUserInfoNo(userId);
		user.setUserName((String)userParams.get("userName"));
		user.setLoginName((String)userParams.get("loginName"));
		userParams.put("password",Constant.SET_PASSWD);
		//user.setPhone((String)userParams.get("phone"));
		user.setCreateTime(DateUtils.dateFormat(new Date(), "yyyy/MM/dd HH:mm:ss"));
		//user.setStatus(Constant.AU_STATUE_YES);//默认有效
		// 盐值
		String salt = Sm3Encrypt.getSaltString();

		//user.setSalt(salt);
		// 新密码
		String newPassword =Sm3Encrypt.encrypt(salt, (String)userParams.get("password"), (String)userParams.get("loginName"));
		System.out.println("=========================================================================");
		System.out.println("==========================="+newPassword+"===============================");
		System.out.println("=========================================================================");
		//密码加密-----需要修改
		user.setPwd(newPassword);
		this.auUserMapper.insert(user);
	}

	public void delSysUserByUserId(Map<String, Object> map, HttpServletRequest request) {
		String ids = (String)map.get("ids");
		if(StringUtil.isNotEmpty(ids)) {
			String[] idArr = ids.split(",");
			for ( String id : idArr ) {
				//删除人
				auUserMapper.deleteByPrimaryKey(id);
				//删除人的角色
				auRoleMapper.deleteSysRolesByUserid(id);
			}
		}
	}

	/**
	 * @author yangcd
	 * 根据用户编号查询用户信息
	 * @param uid 用户主键编号
	 * @return auUser 用户对象
	 * */
	public SysUserInfo findUserById(String uid) {
		return auUserMapper.selectByPrimaryKey(uid);
	}

	public SysUserInfo findUserByOpenId(String openId) {
		return auUserMapper.selectByOpenId(openId);
	}
	/**
	 * @方法名：selectAll
	 * @功能说明：查询所有用户
	 * @author shic
	 * @date  2019年8月5日 下午4:39:22
	 * @param request
	 * @return
	 */
	public PageInfo<SysUserInfo> selectAll(Map<String, Object> map, HttpServletRequest request) {
		// 获取当前操作人
		SysUserInfo user = (SysUserInfo) request.getSession().getAttribute(Constant.LOGIN_USER);
		if(user == null) {
			throw new CustomException(9992,"登录人已失效");
		}
		String auId = user.getUserInfoNo();
		String userName = (String) map.get("userName");
		String loginName = (String) map.get("loginName");
		String phone = (String) map.get("phone");
		map.put("phone", phone);
		map.put("userName", userName);
		map.put("loginName", loginName);
		map.put("userType", "user");
		PageHelper.startPage(Integer.parseInt(map.get("currentPage").toString()), Integer.parseInt(map.get("pageSize").toString()),true);
		List<SysUserInfo> selectUser = auUserMapper.selectAll(map);
		final PageInfo<SysUserInfo> pageInfo = new PageInfo<SysUserInfo>(selectUser);
		return pageInfo;
	}


	public String updateRolesByAuid(Map<String,Object> userParams, SysUserInfo loginUser) throws ParseException {
		//删除原本的角色
		auUserRoleMapper.deleteByAuid(userParams.get("auId").toString());
		//重新新增角色与用户关系
		String roleIds = (String)userParams.get("roleIds");
		if(StringUtils.isNotEmpty(roleIds)) {
			for(int i = 0 ; i < roleIds.split(",").length ; i++) {
				if(StringUtil.isNotEmpty(roleIds.split(",")[i])) {
					String roleuserId = IdUtils.getRandomIdByUUID();
					AuUserRole ur = new AuUserRole();
					ur.setAurCreateTime(DateUtils.dateFormat(new Date(), "yyyy/MM/dd HH:mm:ss"));
					ur.setAurCreateUser(loginUser.getUserInfoNo());
					ur.setAurId(roleuserId);
					ur.setAuId(userParams.get("auId").toString());
					ur.setArId(roleIds.split(",")[i]);
					this.auUserRoleMapper.insert(ur);
				}
			}
		}
		return "success";
	}
	
	
	/**
	 * @方法名：queryInfoById
	 * @功能说明：首页名片
	 * @author yangyuan3
	 * @date  2019年9月7日 下午12:00:59
	 * @param auId
	 * @return
	 * @throws ParseException
	 */
	public Map<String,Object> queryInfoById(String auId) throws ParseException {
		Map<String,Object> obj = auUserMapper.queryInfoById(auId);
		return obj;
	}
	
	/**
	 * 根据用户信息生成加密密码
	 * */
	public SysUserInfo encryptPassword(SysUserInfo user) {
        // User对象包含最基本的字段Username和Password
    	String salt = Sm3Encrypt.getSaltString();
        //user.setSalt(salt);
        // 将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据，散列过程使用了盐
        String newPassword =Sm3Encrypt.encrypt(salt, user.getPwd(), user.getLoginName());
        user.setPwd(newPassword);
		user.setSalt(salt);
        return user;
    }

	/**
	 * 根据用户loginName查询系统内用户信息
	 * @author yangcd
	 * @param loginName 登录名
	 * @throws Exception 
	 * */
	public List<Map<String, Object>> getUserListByUserName(String loginName) throws Exception{
		List<Map<String, Object>> list = auUserMapper.getUserListByUserName(loginName);
		return list;
	}

	/**
	 * @方法名：updatePassword
	 * @功能说明：修改密码
	 * @author yangyuan3
	 * @date  2019年9月9日 下午3:50:50
	 * @param user
	 */
	public void updatePassword(SysUserInfo user) {
		user = encryptPassword(user);
		auUserMapper.updatePasswordByAuId(user.getUserInfoNo(), user.getPwd(), user.getSalt());

	}

	/**
	 * @方法名：resetPassword
	 * @功能说明：重置密码
	 * @author yangyuan3
	 * @date  2019年9月9日 下午4:05:40
	 */
	public void resetPassword(String userInfoNo, String loginName) {
		// 盐值
		String salt = Sm3Encrypt.getSaltString();
		// 新密码
		String newPassword =Sm3Encrypt.encrypt(salt, Constant.SET_PASSWD, loginName);
		// 重置
		auUserMapper.updatePasswordByAuId(userInfoNo, newPassword, salt);
	}

	public List<SysUserInfo> searchUserByOpenid(String openid) {
		return auUserMapper.searchUserByOpenid(openid);
	}

	public void updateUserImage(String userId, String userImage) {
		auUserMapper.updateUserImage(userId, userImage);
	}

	public Map<String, Object> searchUserAllInfo(String userId) throws Exception{
		return auUserMapper.searchUserAllInfo(userId);
	}

	public void updateUserNickName(String userId, String nickName) {
		auUserMapper.updateUserNickName(userId, nickName);
	}

	public PageInfo<SysUserInfo> selectAllCustomer(Map<String, Object> map, HttpServletRequest request) {
		// 获取当前操作人
		SysUserInfo user = (SysUserInfo) request.getSession().getAttribute(Constant.LOGIN_USER);
		if(user == null) {
			throw new CustomException(9992,"登录人已失效");
		}
		String userName = (String) map.get("userName");
		String loginName = (String) map.get("loginName");
		String phone = (String) map.get("phone");
		map.put("phone", phone);
		map.put("userName", userName);
		map.put("loginName", loginName);
		map.put("userType", "customer");
		PageHelper.startPage(Integer.parseInt(map.get("currentPage").toString()), Integer.parseInt(map.get("pageSize").toString()),true);
		List<SysUserInfo> selectUser = auUserMapper.selectAll(map);
		final PageInfo<SysUserInfo> pageInfo = new PageInfo<SysUserInfo>(selectUser);
		return pageInfo;
	}

	/**
	 * 不添加任何条件查询所有用户名
	 * */
	public List<SysUserInfo> queryAllUserNameList() throws Exception{
		return auUserMapper.queryAllUserNameList();
	}
}
